package com.card.hwatt.service.impt;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.card.hwatt.dao.*;
import com.card.hwatt.dto.PageParam;
import com.card.hwatt.dto.PageResult;
import com.card.hwatt.dto.ReturnValue;
import com.card.hwatt.entity.*;
import com.card.hwatt.service.*;

@Service("leaveService")
public class LeaveServiceImpt extends BaseServiceImpt<Leave> implements
		LeaveService {

	@Autowired
	@Qualifier("leaveDao")
	private LeaveDao dao;

	@Override
	protected BaseDao<Leave> getDao() {
		return dao;
	}

	@Override
	public ReturnValue save(long employeeId, String key, String value,
			Date startDate, long day, String reason) {

		String pattern = "yyyyMMdd";
		Date date = new Date();
		for (int i = 0; i <= day; i++) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startDate);
			calendar.add(Calendar.DATE, i);
			String name = DateFormatUtils.format(calendar, pattern);

			List<Object> params = new ArrayList<Object>();
			params.add(employeeId);
			params.add(name);
			PageResult<Leave> list = loadAll(new PageParam(0, 0,
					" employee.id = ? and name = ? ", params, " name desc "));
			if (list != null && CollectionUtils.isNotEmpty(list.rows)) {
				for (Leave l : list.rows) {
					dao.delete(l.id);
				}
			}

			Leave leave = new Leave();
			leave.id = UUID.randomUUID();
			leave.employee = new Employee();
			leave.employee.id = employeeId;
			leave.date = date;
			leave.key = key;
			leave.value = value;
			leave.reason = reason;

			leave.name = name;

			dao.save(leave);
		}

		ReturnValue result = new ReturnValue();
		result.message = "ok";
		result.isSucess = true;
		return result;
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@Override
	public PageResult<Object[]> loadAllGroup(int departmentId, String name,
			String startDate, String endDate, int page, int rows) {
		return dao.loadAllGroup(departmentId, name, startDate, endDate, page,
				rows);
	}
}
